<template>
	<!-- registerPay页面，也是跳转支付页面 -->
  <div class="payment-container">
    <van-nav-bar
      title="挂号支付"
      left-text="返回"
      left-arrow
      @click="onBack"
    />

    <div class="payment-content">
      <!-- 就诊人信息 -->
      <div class="patient-card">
        <van-cell title="就诊人" :value="currentPatient.name" />
        
        <van-cell v-if="currentPatient.phone" title="联系电话" :value="maskPhone(currentPatient.phone)" />
      </div>

      <!-- 医生和预约信息 -->
      <div class="info-card">
        <div class="doctor-info">
          <van-image
            :src="doctorDetail.avatar || defaultAvatar"
            width="60"
            height="60"
            round
            lazy-load
          />
          <div class="doctor-detail">
            <div class="doctor-name">
              {{ doctorDetail.name || '未知医生' }}
              <span class="doctor-title">{{ doctorDetail.title || '' }}</span>
            </div>
            <div class="doctor-dept">{{ department || '未知科室' }}</div>
            <div v-if="doctorDetail.specialty" class="doctor-specialty">
              专长：{{ doctorDetail.specialty }}
            </div>
          </div>
        </div>

        <van-divider />

        <div class="appointment-info">
          <div class="info-item">
            <van-icon name="clock-o" />
            <span
              >就诊时间：{{ scheduleDetail.visit_date || '未指定' }}
              {{ scheduleDetail.time_slot === 1 ? '上午' : '下午' }}</span
            >
          </div>
          <div class="info-item">
            <van-icon name="location-o" />
            <span>就诊地点：{{ hospital }} {{ department || '未知科室' }}诊室</span>
          </div>
          <div class="info-item">
            <van-icon name="medal-o" />
            <span>就诊序号：{{ scheduleDetail.visit_no || '待分配' }}</span>
          </div>
          <div
            v-if="scheduleDetail.start_time && scheduleDetail.end_time"
            class="info-item"
          >
            <van-icon name="clock" />
            <span
              >具体时间：{{ scheduleDetail.start_time }} -
              {{ scheduleDetail.end_time }}</span
            >
          </div>
        </div>
      </div>

      <!-- 支付金额 -->
      <div class="amount-card">
        <div class="amount-title">支付金额</div>
        <div class="amount-value">¥{{ formatPrice(scheduleDetail.price) }}</div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-methods">
        <div class="section-title">选择支付方式</div>
        <van-radio-group v-model="paymentMethod">
          <van-cell-group>
            <van-cell title="微信支付" clickable @click="paymentMethod = 'wechat'">
              <template #right-icon>
                <van-radio name="wechat" />
              </template>
              <template #icon>
                <van-icon name="wechat" size="20" color="#07C160" />
              </template>
            </van-cell>

            <van-cell title="支付宝" clickable @click="paymentMethod = 'alipay'">
              <template #right-icon>
                <van-radio name="alipay" />
              </template>
              <template #icon>
                <van-icon name="alipay" size="20" color="#1677FF" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>

      <!-- 症状描述 -->
      <van-form>
        <div class="symptom-input">
          <van-field
            v-model="symptoms"
            label="症状描述"
            type="textarea"
            placeholder="请简要描述您的症状（必填）"
            rows="3"
            autosize
            :rules="[{ required: true, message: '请简要描述您的症状', trigger: 'blur' }]"
          />
        </div>
      </van-form>
    </div>

    <!-- 底部支付按钮 -->
    <div class="payment-footer">
      <div class="price-display">
        <span>合计：</span>
        <span class="price">¥{{ formatPrice(scheduleDetail.price) }}</span>
      </div>
      <van-button
        round
        type="primary"
        class="pay-button"
        @click="onPay"
        :loading="isPaying"
      >
        立即支付
      </van-button>
    </div>

    <!-- 支付成功弹窗 -->
    <van-popup 
      v-model:show="showSuccess" 
      round 
      position="center" 
      style="{ width: '85%', max-width: '500px' }"
      :close-on-click-overlay="false"
      @open="onSuccessPopupOpen"
    >
      <div class="success-popup">
        <div class="success-icon-container">
          <van-icon name="checked" size="50" color="#07C160" />
        </div>
        <div class="success-title">支付成功</div>
        <div class="success-message">您的挂号已成功预约</div>
        
        <div class="order-info">
          <div class="info-row">
            <span class="info-label">订单号：</span>
            <span class="info-value">{{ payNo || '系统生成中...' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">医生：</span>
            <span class="info-value">{{ doctorDetail.name || '未知医生' }} ({{ doctorDetail.title || '未知职称' }})</span>
          </div>
          <div class="info-row">
            <span class="info-label">科室：</span>
            <span class="info-value">{{ department || '未知科室' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">就诊时间：</span>
            <span class="info-value">
              {{ scheduleDetail.visit_date || '未指定' }}
              {{ scheduleDetail.time_slot === 1 ? '上午' : '下午' }}
            </span>
          </div>
          <div v-if="scheduleDetail.start_time && scheduleDetail.end_time" class="info-row">
            <span class="info-label">具体时段：</span>
            <span class="info-value">{{ scheduleDetail.start_time }} - {{ scheduleDetail.end_time }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">就诊序号：</span>
            <span class="info-value">{{ scheduleDetail.visit_no || '待分配' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">就诊人：</span>
            <span class="info-value">{{ currentPatient.name || '未知' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">支付金额：</span>
            <span class="info-value">¥{{ formatPrice(scheduleDetail.price) }}</span>
          </div>
          <div class="info-row reminder">
            <van-icon name="info-o" size="14" color="#1989fa" />
            <span>请提前30分钟到达医院，并携带有效身份证件</span>
          </div>
        </div>
        
        <div class="popup-buttons">
          <van-button 
            type="default" 
            class="secondary-button"
            @click="onGoHome"
          >
            返回首页
          </van-button>
          <van-button 
            type="primary" 
            class="primary-button"
            @click="onViewOrder"
          >
            查看订单详情
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showFailToast, showConfirmDialog } from 'vant'
import axios from 'axios'
import { useUserStore } from '../stores/user.js'
import { useRegisterStore } from '../stores/register.js'

// 获取数据的多种方式
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const registerStore = useRegisterStore()
const { proxy } = getCurrentInstance();

// 页面状态管理
const symptoms = ref('')
const isPaying = ref(false)
const showSuccess = ref(false)
const payNo = ref('')
const paymentMethod = ref('wechat')
const defaultAvatar = 'https://picsum.photos/id/237/200/200' // 默认医生头像

// 计算属性 - 从Store获取数据
const currentPatient = computed(() => userStore.getDefaultPatient() || {})
const doctorDetail = computed(() => registerStore.doctorDetail || {})
const scheduleDetail = computed(() => registerStore.scheduleDetail || {})
const department = computed(() => registerStore.department || '')
const hospital = ref('本院') // 医院名（可固定或接口返回）

// 从路由参数获取record_id和order_id
const routeRecordId = ref(route.query.recordId);
const routeOrderId = computed(() => route.query.orderId);

// 从Pinia store获取完整订单和支付信息
const orderInfo = ref( registerStore.currentOrder);
const paymentInfo = ref(registerStore.currentPayment );

// 最终使用的record_id - 优先级: 路由参数 > Pinia存储
const recordId = computed(() => {
  return routeRecordId.value || paymentInfo.value?.record_id;
});

// 最终使用的order_id
const orderId = computed(() => {
  return routeOrderId.value || orderInfo.value?.order_id;
});

/* 工具：身份证掩码 */
function maskIdCard(idCard) {
  if (!idCard || idCard.length !== 18) return idCard
  return idCard.replace(/^(\d{6})\d+(\d{4})$/, '$1********$2')
}

/* 工具：手机号掩码 */
function maskPhone(phone) {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/^(\d{3})\d+(\d{4})$/, '$1****$2')
}

/* 工具：格式化价格 */
function formatPrice(price) {
  if (!price && price !== 0) return '0.00'
  return parseFloat(price).toFixed(2)
}

/* 支付成功弹窗打开时的动画效果 */
function onSuccessPopupOpen() {
  // 可以在这里添加弹窗打开时的动画逻辑
  const popupEl = document.querySelector('.success-popup');
  if (popupEl) {
    popupEl.classList.add('popup-enter');
    setTimeout(() => {
      popupEl.classList.remove('popup-enter');
    }, 500);
  }
}


onMounted(() => {
  // 优先从路由参数获取
  recordId.value = route.query.recordId || registerStore.currentPayment?.record_id;
  orderId.value = route.query.orderId || registerStore.currentOrder?.order_id;

console.log("获取订单号传递",recordId)
console.log("这是orderid",orderId)
  console.log('支付页面初始化:', {
    routeParams: route.query,
    piniaData: {
      order: registerStore.currentOrder,
      payment: registerStore.currentPayment
    }
  });

  if (!orderId.value) {
    showConfirmDialog({
      title: '提示',
      message: '订单信息缺失，请重新预约',
      confirmButtonText: '返回挂号页',
      showCancelButton: false
    }).then(() => {
      router.push('/register');
    });
    return;

}
  // 尝试从本地获取默认就诊人信息
  const defaultPatient = userStore.getDefaultPatient();
  if (defaultPatient) {
    // 这里使用$set确保响应式更新
// 直接赋值替代 proxy.$set
    currentPatient.value.name = defaultPatient.name;
    currentPatient.value.id_card = defaultPatient.id_card || '';
    currentPatient.value.phone = defaultPatient.phone || '';
    currentPatient.value.patient_id = defaultPatient.patient_id;
  }

  //http://127.0.0.1:8080/api/v1/registration/{orderId}
  console.log('订单号创建的',orderId)
  axios.get(`/api/v1/registration/${orderId.value}`)
    .then(({ data }) => {
		console.log("这是支付的data",data)
      if (data.code == 0) {
        const o = data.data
        // 填充所有缺失字段
		currentPatient.value.name = o.patient_name;
		currentPatient.value.id_card = o.patient_id_card;
		currentPatient.value.phone = o.patient_phone;
		currentPatient.value.patient_id = o.patient_id;

		doctorDetail.value.name = o.doctor_name;
		doctorDetail.value.title = o.doctor_title;
		doctorDetail.value.id = o.doctor_id;
		doctorDetail.value.avatar = o.doctor_avatar || defaultAvatar;
		doctorDetail.value.specialty = o.doctor_specialty;

		scheduleDetail.value.visit_date = o.visit_date;
		scheduleDetail.value.time_slot = o.time_slot;
		scheduleDetail.value.price = o.amount;
		scheduleDetail.value.visit_no = o.visit_no;
		scheduleDetail.value.start_time = o.start_time;
		scheduleDetail.value.end_time = o.end_time;

		department.value = o.dept_name || '未知科室';
      } else {
        showConfirmDialog({
          title: '获取失败',
          message: data.message || '获取订单详情失败',
          confirmButtonText: '返回挂号页',
          showCancelButton: false
        }).then(() => {
          router.push('/register');
        });
      }
    })
    .catch(err => {
      console.error(err);
      // 如果API获取失败，但本地有默认就诊人信息，可以继续显示页面
      if (defaultPatient && defaultPatient.patient_id) {
        showToast({
          message: '已使用默认就诊人信息，部分数据可能不完整',
          duration: 3000,
        });
      } else {
        showConfirmDialog({
          title: '获取失败',
          message: '获取订单详情失败，请重新操作',
          confirmButtonText: '返回挂号页',
          showCancelButton: false
        }).then(() => {
          router.push('/register');
        });
      }
    })
})

// 支付处理函数
async function onPay() {
  if (!symptoms.value.trim()) {
    showFailToast('请填写症状描述');
    return;
  }
  
  if (!recordId.value) {
    showFailToast('未找到支付记录信息');
    return;
  }

  isPaying.value = true;



  if (!recordId.value) {
	// 尝试从store获取
	recordId.value = registerStore.currentPayment?.record_id;
	
	if (!recordId.value) {
	  console.error('支付记录ID缺失:', {
		routeParams: route.query,
		piniaData: registerStore.currentPayment
	  });
	  showFailToast('支付信息不完整，请重新预约');
	  return;
	}}
  try {
    // 更新症状 - 使用orderId
    if (orderId.value) {
      await axios.put(`/api/v1/registration/${orderId.value}`, {
        symptoms: symptoms.value
      });
    }

    // 标记已支付 - 使用recordId
	//http://127.0.0.1:8080/api/v1/payment/markPaid/{record_id}
	console.log("测试订单号",recordId)
    const { data } = await axios.put(`/api/v1/payment/markPaid/${recordId.value}`);
     console.log('支付响应:', data); // 添加调试日志
    if (data.code === 0) {
      payNo.value = data.data.order_no;
        showSuccess.value = true;
      // 支付成功后清空Pinia中的临时数据
      registerStore.clearOrderData();
    } else {
      showFailToast(data.message || '支付失败，请重试');
    }
  } catch (e) {
    console.error(e);
    showFailToast('支付失败，请检查网络后重试');
  } finally {
    isPaying.value = false;
  }
}

/* 导航函数 */
function onBack() {
  router.back()
}

function onViewOrder() {
  showSuccess.value = false;
    router.push({ path: '/register', query: { mainTab: 1 } });

}

function onGoHome() {
  showSuccess.value = false;
  // 延迟跳转，等待弹窗关闭动画完成
    router.push('/home');
}
</script>

<style scoped>
.payment-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.payment-content {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.patient-card {
  background: #fff;
  border-radius: 12px;
  margin-bottom: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.info-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.doctor-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.doctor-detail {
  flex: 1;
}

.doctor-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.doctor-title {
  font-size: 14px;
  color: #1989fa;
  font-weight: normal;
  margin-left: 6px;
  background-color: #e8f3ff;
  padding: 2px 6px;
  border-radius: 4px;
}

.doctor-dept {
  font-size: 14px;
  color: #666;
  margin-bottom: 2px;
}

.doctor-specialty {
  font-size: 13px;
  color: #888;
}

.appointment-info {
  font-size: 14px;
  margin-top: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  color: #333;
  line-height: 1.5;
}

.info-item .van-icon {
  margin-right: 8px;
  color: #1989fa;
  font-size: 16px;
}

.amount-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.amount-title {
  font-size: 16px;
  color: #333;
}

.amount-value {
  font-size: 24px;
  font-weight: bold;
  color: #ee0a24;
}

.payment-methods {
  background: #fff;
  border-radius: 12px;
  margin-bottom: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
  padding: 16px 16px 8px;
  font-size: 15px;
  color: #333;
  font-weight: bold;
}

.van-cell {
  align-items: center;
  padding: 12px 16px;
}

.van-cell__left-icon {
  margin-right: 8px;
}

.symptom-input {
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.payment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.price-display {
  font-size: 16px;
  display: flex;
  align-items: center;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #ee0a24;
  margin-left: 4px;
}

.pay-button {
  width: 140px;
  height: 45px;
  font-size: 16px;
}

/* 支付成功弹窗样式 */
.success-popup {
  padding: 24px 16px;
  text-align: center;
  transform: scale(0.95);
  transition: transform 0.3s ease;
}

.popup-enter {
  transform: scale(1);
}

.success-icon-container {
  width: 80px;
  height: 80px;
  margin: 0 auto 16px;
  background-color: #f0f9f4;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.success-title {
  font-size: 22px;
  font-weight: bold;
  margin: 8px 0 12px;
  color: #333;
}

.success-message {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
  padding: 0 10px;
}

.order-info {
  text-align: left;
  font-size: 14px;
  margin: 16px 0;
  padding: 16px;
  background: #f7f8fa;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
}

.info-row {
  display: flex;
  margin: 10px 0;
  line-height: 1.5;
  flex-wrap: wrap;
}

.info-label {
  color: #888;
  min-width: 80px;
}

.info-value {
  color: #333;
  flex: 1;
  word-break: break-word;
}

.reminder {
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px dashed #e0e0e0;
  color: #1989fa;
  font-size: 13px;
  align-items: center;
}

.reminder .van-icon {
  margin-right: 6px;
}

.popup-buttons {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.secondary-button {
  flex: 1;
  height: 44px;
}

.primary-button {
  flex: 1;
  height: 44px;
}

/* 适配小屏幕设备 */
@media (max-width: 375px) {
  .doctor-name {
    font-size: 16px;
  }
  
  .amount-value {
    font-size: 22px;
  }
  
  .success-title {
    font-size: 20px;
  }
}
</style>
